<?php

namespace App\Http\Controllers\Api;

use App\Models\Film;
use GuzzleHttp\Client;
use Illuminate\Http\Request;
use App\Http\Controllers\Controller;

class FilmController extends Controller
{
    /**
     * @return \Illuminate\Contracts\Pagination\Paginator
     */
    public function index()
    {
//        return Film::select('id', 'title', 'cover')->orderByDesc('id')->simplePaginate(100);
        return [];
    }

    /**
     * @param $id
     * @return \Illuminate\Database\Eloquent\Collection|\Illuminate\Database\Eloquent\Model
     */
    public function show($id)
    {
        // 实例化cli
        $client = new Client();

        // http请求参数
        $options = config('films.options');

        $page = $client->request('GET', config('films.baseUrl') . 'show/' . $id . '.html', $options);
        $pageContent = $page->getBody();

        $regexCount = '/第(\d+)集/';
        $regexCount2 = '/第(\d+)期/';
        $regexTitle = '/dt class=\"name">(.*)<span/';


        $regexURL = "/<iframe.*src=\"(.*?)\"/";
        $regexVideoSrc = '/<video.*src="(.*?)"/';

        // 当不能正常播放时使用
        $regexCode = '/encodeURI.+get.+\"(.+)\"\)/';
        $regexURI = '/.post.+\"(.+hp)\"/';
        $regexBasePlayUrl = '/video.+=\"(.+url=)/';
        $regexBaseApiUrl = '/(htt.+om\/)/';

        preg_match_all($regexCount, $pageContent, $matchCounts);
        $count = isset($matchCounts[1]) ? $matchCounts[1] : null;
        preg_match_all($regexCount2, $pageContent, $matchCounts);
        $count2 = isset($matchCounts[1]) ? $matchCounts[1] : null;
        preg_match($regexTitle, $pageContent, $matchTitle);
        $title = isset($matchTitle[1]) ? $matchTitle[1] : null;


        $count = $count ?: $count2;

        if ($count) {
            $firstOne = reset($count) + 0;
            $lastOne = end($count);

            while ($firstOne <= $lastOne) {
                $pageDetial = $client->request('GET', config('films.baseUrl') . 'play/' . $id . '/1/' . $firstOne . '.html', $options);
                $pageDetialContent = $pageDetial->getBody();
                preg_match($regexURL, $pageDetialContent, $matchUrls);

                $url = isset($matchUrls[1]) ? $matchUrls[1] : null;

                preg_match($regexBaseApiUrl, $url, $matchBaseApiUrl);
                $baseApiUrl = $matchBaseApiUrl[1];

                if ($url) {
                    // 去请求播放页
                    $playPage = $client->request('GET', $url, $options);
                    $playPageContent = $playPage->getBody();

                    if (!strpos($playPageContent, "$.post")) {
                        preg_match($regexVideoSrc, $playPageContent, $matchSrc);
                        $videoSrc[$firstOne] = $matchSrc[1];

                    } else {
                        // 正则获取信息
                        preg_match($regexCode, $playPageContent, $matchCode);
                        $code = getEncode($matchCode[1]);
                        preg_match($regexURI, $playPageContent, $matchURI);
                        $uri = $matchURI[1];

                        $response = $client->request('POST', $baseApiUrl . $uri, [
                            'form_params' => [
                                'key' => $code,
                                'v' => 'https://www.zxfuli.com',
                                'from' => '',
                                't' => 'phone',
                                'up' => '0',
                                'ptype' => '',
                            ]
                        ]);

                        $data = $response->getBody()->getContents();
                        $data = collect(json_decode($data))->toArray();
                        if (strpos($uri, 'm5')) {

                            preg_match($regexBasePlayUrl, $playPageContent, $matchBasePlayUrl);
                            $matchBaseApiUrl[0];
                            $basePlayUrl = $matchBasePlayUrl[1];
                            if (isset($data['success']) ) {
                                if($data['success'] == '0'){
                                    $url = $basePlayUrl . $data['url'];

                                }else {
                                    $url = $data['url'];
                                }

                            }else if (isset($data['play'])){
                                $url = $data['url'];
                            }
                        } else {
                            $url = $data['url'];
                        }

                         $videoSrc[$firstOne] = $url;
                    }

                    // 获取video的src
                }

                ++$firstOne;
            }

        } else {
            $pageDetial = $client->request('GET', config('films.baseUrl') . 'play/' . $id . '/1/1.html', $options);
            $pageDetialContent = $pageDetial->getBody();
            preg_match($regexURL, $pageDetialContent, $matchUrls);
            $url = isset($matchUrls[1]) ? $matchUrls[1] : null;

            preg_match($regexBaseApiUrl, $url, $matchBaseApiUrl);
            $baseApiUrl = $matchBaseApiUrl[1];

            if ($url) {
                // 去请求播放页
                $playPage = $client->request('GET', $url, $options);
                $playPageContent = $playPage->getBody();

                if (!strpos($playPageContent, "$.post")) {
                    preg_match($regexVideoSrc, $playPageContent, $matchSrc);
                    $videoSrc[1] = $matchSrc[1];

                } else {
                    // 正则获取信息
                    preg_match($regexCode, $playPageContent, $matchCode);
                    $code = getEncode($matchCode[1]);
                    preg_match($regexURI, $playPageContent, $matchURI);
                    $uri = $matchURI[1];

                    $response = $client->request('POST', $baseApiUrl . $uri, [
                        'form_params' => [
                            'key' => $code,
                            'v' => 'https://www.zxfuli.com',
                            'from' => '',
                            't' => 'phone',
                            'up' => '0',
                            'ptype' => '',
                        ]
                    ]);

                    $data = $response->getBody()->getContents();
                    $data = collect(json_decode($data))->toArray();

                    if (strpos($uri, 'm5')) {

                        preg_match($regexBasePlayUrl, $playPageContent, $matchBasePlayUrl);
                        $matchBaseApiUrl[0];
                        $basePlayUrl = $matchBasePlayUrl[1];
                        if ($data['success'] == '0') {
                            $url = $basePlayUrl . $data['url'];

                        } else {
                            $url = $data['url'];
                        }
                    } else {
                        $url = $data['url'];
                    }


                    return [
                        'title' => $title,
                        'video' => [
                            '1' => $url
                        ]
                    ];

                }

                // 获取video的src
                $videoSrc[1] = $matchSrc[1];
            }

        }


        return [
            'title' => $title,
            'video' => $videoSrc
        ];


    }

    /**
     * @param Request $request
     * @return \Illuminate\Contracts\Pagination\Paginator
     */
    public function search(Request $request)
    {

        $q = $request->input('q', '');


        // 实例化cli
        $client = new Client();

        // http请求参数
        $options = config('films.options');

        $page = $client->request('GET', config('films.baseUrl') . 'search?wd=' . $q, $options);
        $pageContent = $page->getBody();

        $regexId = '/link-hover.+show\/(\d+)\.html/'; // 匹配所以id
        $regexCover = '/src="(.+.jpg)\"/';  // 匹配所有封面
        $regexTitle = '/title=\"(.+)\"><i/';  // 匹配所有title
        preg_match_all($regexId, $pageContent, $matchIds);
        preg_match_all($regexCover, $pageContent, $matchCovers);
        preg_match_all($regexTitle, $pageContent, $matchTitles);

        $ids = $matchIds[1];
        $covers = $matchCovers[1];
        $titles = $matchTitles[1];

        $films = [];
        $i = 0;
        foreach ($ids as $k => $v) {
            ++$i;

            if (!strpos($covers[$k], 'yy')) {
                $films[$i]['id'] = $v;
                $films[$i]['cover'] = $covers[$k];
                $films[$i]['title'] = $titles[$k];
            }
        }

        return [
            'data' => $films
        ];

        $query = Film::select('id', 'cover', 'title');
        if ($q) {
            $query->where('title', 'like', '%' . $q . '%')->orWhere('desc', 'like', '%' . $q . '%');
        }

        return $query->simplePaginate(100);

    }
}
